<template>
  <div class="application-list-container">
    <el-card>
      <el-table
        :data="applicationList"
        border
        stripe
        v-loading="isLoading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="_id" label="申请ID" width="200" />
        <el-table-column prop="user_id.name" label="申请人姓名" width="120" />
        <el-table-column prop="appliedRole" label="申请权限" width="120" />
        <el-table-column prop="status" label="状态" width="100" />

        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              v-if="scope.row.status === '待审核'"
              @click="handleAudit(scope.row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 审核模态框 -->
      <el-dialog
        v-model="showAuditDialog"
        title="审核申请"
        width="30%"
        :before-close="handleDialogClose"
      >
        <el-form :model="auditForm" label-width="80px"> </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAuditDialog = false">取消</el-button>
            <el-button type="danger" @click="confirmAudit('reject')">拒绝</el-button>
            <el-button type="success" @click="confirmAudit('approve')">通过</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {
  getApplicationList,
  rejectApplication,
  updateUserRole,
  approveApplication,
} from '@/api/user'
import { ElMessage } from 'element-plus'

// 状态管理
const applicationList = ref([])
const isLoading = ref(false)
const showAuditDialog = ref(false)
const currentApplication = ref(null) // 当前审核的申请
const auditForm = ref({ reason: '' }) // 审核表单（拒绝原因）
const auditType = ref('') // 当前审核类型（approve/reject）

// 角色文本映射
const roleMap = {
  1: '客服',
  2: '站点',
  3: '维修员',
}

// 获取申请列表
const fetchApplicationList = async () => {
  isLoading.value = true
  try {
    const res = await getApplicationList({ status: '待审核' }) // 只获取待审核的申请
    if (res.code === 200) {
      applicationList.value = res.data.map((item) => ({
        ...item,
        appliedRole: roleMap[item.applied_role], // 转换权限类型为文本
        status: item.status || '待审核',
      }))
    }
  } catch (err) {
    ElMessage.error('获取申请列表失败', err)
  } finally {
    isLoading.value = false
    console.log(applicationList.value)
  }
}

// 点击审核按钮
const handleAudit = (row) => {
  currentApplication.value = row
  showAuditDialog.value = true
  auditType.value = 'approve' // 默认显示通过按钮
  auditForm.value.reason = '' // 清空原因
}

// 确认审核
const confirmAudit = async (type) => {
  console.log(currentApplication.value)

  if (!currentApplication.value) return

  try {
    if (type === 'approve') {
      if (currentApplication.value.station_id) {
        // 站点权限申请：调用站点加入接口
        await approveApplication(currentApplication.value._id)
        ElMessage.success('站点权限申请通过')
        fetchApplicationList()
        showAuditDialog.value = false
        return
      }
      // 通过申请：更新用户角色
      await updateUserRole({
        userId: currentApplication.value.user_id,
        newRole: currentApplication.value.applied_role, // 申请的权限类型
      })
      // 这里可补充更新申请状态为已通过的接口（假设后端自动处理或需要额外调用）
      ElMessage.success('申请通过，用户权限已更新')
    } else {
      // 拒绝申请
      await rejectApplication(currentApplication.value.id, {
        reason: auditForm.value.reason,
      })
      ElMessage.success('申请已拒绝')
    }

    // 刷新列表
    fetchApplicationList()
    showAuditDialog.value = false
  } catch (err) {
    ElMessage.error('审核操作失败', err)
  }
}

// 关闭模态框
const handleDialogClose = () => {
  showAuditDialog.value = false
  currentApplication.value = null
}

// 组件挂载时加载数据
fetchApplicationList()

// 辅助函数：转换角色为文本
// const getRoleText = (role) => roleMap[role] || '未知权限'
</script>

<style scoped>
.application-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
</style>
